package com.bluedon.ism.commons.dao;

import com.bluedon.ism.commons.entity.Account;
import com.bluedon.ism.commons.entity.AccountRole;
import com.bluedon.ism.commons.entity.RolePermission;
import com.bluedon.ism.commons.util.DateUtil;
import com.bluedon.ism.commons.util.Pager;
import com.bluedon.ism.commons.util.StringUtil;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository("accountDAO")
public class AccountDAO extends BaseDAO {

	public void addAccount(Account account) {
		this.save(account);
	}
	
	public void updateAccount(Account account) {
		this.update(account);
	}
	
	public Account getAccountById(Long id) {
		return (Account) this.findObjectById(Account.class, id);
	}
	
	public void deleteAccount(Long aid) {
		Account act = this.getAccountById(aid);
		if (act != null) {
			this.delete(act);
		}
	}

	@SuppressWarnings("unchecked")
	private Pager<Account> getAccountPage(int type, int pageNo, int pageSize, 
			String oid, String userName) {
		StringBuffer hql = new StringBuffer("select a from Account a where 1=1 ");
		Map<String,Object> param = new HashMap<String, Object>();
		if (type > -1) {
			hql.append(" and a.type = :type");
			param.put("type", type);
		}
		if (!StringUtil.isBlank(userName)) {
			hql.append(" and a.username like :userName");
			param.put("userName", "%" + userName + "%");
		}
		if (!StringUtil.isBlank(oid)) {
            hql.append(" and a.organization.oid = :oid");
//            hql.append(" and a.organization.oid like '" + oid + "%'");
            param.put("oid", oid);
        }

		hql.append(" order by a.aid desc ");
		return this.findPageList(hql.toString(),param,  pageNo, pageSize);
	}
	
	@SuppressWarnings("rawtypes")
	public Pager getAccountPageByType(int type, int pageNo, int pageSize, String oid, String userName) {
		return getAccountPage(type, pageNo, pageSize, oid, userName);
	}

	public Account getAccountByName(String username) {
		String hql = "from Account a where a.username = ?";
		return (Account) getFirstElement(hql,new Object[]{username});
	}
	
	@SuppressWarnings("unchecked")
	public List<Account> getAccountListByName(String name) {
	    String hql = "from Account a where a.disabled = false and a.username like :username or a.realname like :realname ";
	    Map<String,Object> params = new HashMap<String,Object>();
	    params.put("username", "%" + name + "%");
	    params.put("realname", "%" + name + "%");
	    return getHQLList(hql, params, 0, 10);
	}
	
	public Account getAccountByEmail(String email) {
		String hql = "from Account a where a.email = ?";
		return (Account) getFirstElement(hql,new Object[]{email});
	}

	
	public Account isValidReset(String token, long aid) {
		String currentTime = DateUtil.getCrurentFullTime();
		String hql = "from Account a where to_char(to_date(' " + currentTime + " ','yyyy-mm-dd hh24:mi:ss') - a.resetTime) like '+000000000 00:0%' and a.resetToken = ? and a.aid = ?" ;
		return (Account) getFirstElement(hql,new Object[]{token,aid});
	}
	
	
	public Set<String> getRoleNames(String username) {
		Set<String> roleNames = new HashSet<String>();
		Account account = this.getAccountByName(username);
		Set<AccountRole> set = account.getAccountRoles();
		for (AccountRole ar : set) {
			roleNames.add(ar.getRole().getRoleName());
		}
		return roleNames;
	}
	
	public Set<String> getPermissionsByRoleNames(Set<String> roleNames) {
	    Set<String> permissionNames = new HashSet<String>();
	    for (String roleName : roleNames) {
	        permissionNames.addAll(getPermissionsByRoleName(roleName));
	    }
	    return permissionNames;
	}
	
	
	@SuppressWarnings("unchecked")
	public Set<String> getPermissionsByRoleName(String roleName) {
		Set<String> permissions = new HashSet<String>();
		String hql = " from RolePermission rp where rp.role.roleName = :roleName";
		Map<String, Object> param = new HashMap<String,Object>();
		param.put("roleName", roleName);
		List<RolePermission> rpList = createQuery(hql,param ).list();
		for (RolePermission rp : rpList) {
		    permissions.add(rp.getPermission().getPermissionCode());
		}
		return permissions;
	}
	
	public int deleteManyAccount(String aidArray) {
	    String sql = "delete from account where aid in (" + aidArray + ")";
	    return this.getSession().createSQLQuery(sql).executeUpdate();
	}
	
	@SuppressWarnings("unchecked")
	public Pager<Account> getAidListConfig(Map<String, Object>map,int pageNo,int pageSize){
		String orgId=(String)map.get("orgId");
		Long currAid=Long.parseLong(String.valueOf(map.get("currAid")));//注意点:aid要用valueOf转
		StringBuffer hql=new StringBuffer("from Account a where a.aid not in(:currAid)");
		if(!StringUtil.isBlank(orgId)){
			hql.append(" and a.organization.oid like:orgId");
		}
		Map<String, Object>param = new HashMap<String, Object>();
		param.put("orgId", orgId+"%");
		param.put("currAid", currAid);
		return findPageList(hql.toString(),param, pageNo, pageSize);
	}
	
	@SuppressWarnings("unchecked")
	public Pager<Account> searchAccount(String oid, String name, int pageNo, int pageSize) {
	    StringBuffer hql = new StringBuffer("from Account t where 1=1 ");
	    if (!StringUtil.isBlank(oid)) {
	        hql.append("and t.organization.oid = :oid ");
	    }
	    if (!StringUtil.isBlank(name)) {
	        hql.append("and (t.username like :name or t.realname like :name) ");
	    }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("oid", oid);
        param.put("name", "%" + name + "%");
	    return findPageList(hql.toString(), param, pageNo, pageSize);
	}
	
	/**
	 * 查询与当前用户在同一个分局的账号
	 * @param aid
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Pager<Account> getSameOrgAccount(String keyword, Long oldAid, Long aid, int pageNo, int pageSize){
		StringBuffer hql = new StringBuffer(" from Account a where organization = (select b.organization from Account b where b.aid = :aid)");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("aid", aid);
		if ( oldAid != 0  && oldAid != null){
			hql.append(" and a.aid != :oldAid");
			param.put("oldAid", oldAid);
		}
		if (StringUtil.isNotBlank(keyword)){
			hql.append(" and (a.realname like :keyword or a.email like :keyword or a.mobile like :keyword) ");
			param.put("keyword", "%" + keyword + "%");
		}
		return findPageList(hql.toString(), param, pageNo, pageSize);
	}
	
	/**
	 * 查询所有用户
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Account> findAll(){
		String hql = "from Account";
		return find(hql);
	}
	
}
